<template>
	<view class="page-container bg-white">
		<u-navbar safeAreaInsetTop fixed placeholder title="登录授权" :autoBack="true" />
		<view class="login-wrap">
			<image class="logo" :lazy-load="true" mode="aspectFit" :src="imgBaseUrl + 'login-logo.png'"></image>
			<button
				class="auth-btn"
				:open-type="agree ? 'getPhoneNumber' : ''"
				@getphonenumber="getPhoneNumber"
				@click="checkAgree"
			>
				手机号快捷登录
			</button>
			<view @click="onAgree" class="flex-c fs-24 pt-35">
				<view>
					<label class="agree-radio" v-if="agree">
						<radio value="1" :checked="true" style="transform: scale(0.7)" />
					</label>
					<label class="agree-radio" v-else><radio value="0" style="transform: scale(0.7)" /></label>
				</view>

				<text class="c-black-_4">我已阅读并同意</text>
				<text class="c-brown-bc">《用户协议&隐私协议》</text>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { addSignForLvUser } from "@/utils/tools"
import { $loginOnlyByWeixin, $registerByMobile, $decryptMobile, $code2Session } from "@/api/user"
import useUserStore from "@/store/user"
const userStore = useUserStore()
const imgBaseUrl = inject("imgBaseUrl")
const agree = ref(false)

const onAgree = () => {
	agree.value = !agree.value
}
const checkAgree = (e: any) => {
	if (agree.value) {
		getPhoneNumber(e.mp)
	} else {
		uni.showToast({
			title: "请勾选同意用户协议",
			icon: "none",
		})
	}
}
const autoLogin = () => {
	doWxLogin((openId: string) => {
		$loginOnlyByWeixin({ open_id: openId })
			.then((data) => {
				userStore.updateUser(data)
				goback()
			})
			.catch((err) => {
				console.log(err)
				//登录失败则保持页面不变，让用户点击授权
			})
	})
}
const doWxLogin = (callbackFunc: Function) => {
	var openId = userStore.openId
	if (openId) {
		callbackFunc && callbackFunc(openId)
	} else {
		// 登录
		uni.login({
			success: (res) => {
				$code2Session({
					app_id: userStore.appId,
					code: res.code,
				}).then((data: any) => {
					// 缓存open_id到store
					userStore.updateOpenId(data.open_id)
					callbackFunc && callbackFunc(data.open_id)
				})
			},
		})
	}
}
const getPhoneNumber = (e: any) => {
	if (e.detail.errMsg == "getPhoneNumber:ok") {
		doWxLogin((openId: string) => {
			//open_id 直接登录
			$loginOnlyByWeixin({ open_id: openId })
				.then((data) => {
					//1、登陆成功 缓存openId和用户信息
					userStore.updateUser(data)
					//2、跳转回去
					goback()
				})
				.catch((err) => {
					//如果 openId登录报错走手机号流程
					$decryptMobile({
						encrypted_data: e.detail.encryptedData,
						iv: e.detail.iv,
						open_id: openId,
					})
						.then((data: any) => {
							let timestamp = +new Date().getTime() / 1000
							//拿到手机号注册
							let getParams = {
								under_score: 1,
								timestamp: timestamp,
							}
							let postParams: any = {
								app_id: userStore.appId,
								open_id: openId,
								mobile: data.pure_phone_number,
							}

							addSignForLvUser(getParams, postParams, function (signData) {
								postParams.sign = signData
								postParams.timestamp = timestamp
								// 调用 $registerByMobile(timestamp) 得到userData
								$registerByMobile(postParams).then((data) => {
									userStore.updateUser(data)
									goback()
								})
							})
						})
						.catch((err) => {
							// 清除用户登录缓存
							userStore.updateUser({})
							// 方法
							uni.showModal({
								title: "提示",
								content: err.message,
							})
						})
				})
		})
	} else {
		uni.showModal({
			title: "提示",
			content: e.detail.errMsg,
		})
	}
}
const goback = () => {
	uni.navigateBack()
}
onMounted(() => {
	autoLogin()
})
</script>

<style lang="scss" scoped>
.login-wrap {
	margin-top: 284rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	.logo {
		width: 270rpx;
		height: 84rpx;
		margin-bottom: 164rpx;
	}
	.auth-btn {
		width: 622rpx;
		height: 88rpx;
		line-height: 88rpx;
		font-size: 28rpx;
		font-weight: bold;
		background: $c-theme;
		border-radius: 48rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
}
</style>
